/**
 * Created by yijx on 2017/3/13.
 */
//当前选中任务
var selectedTask = [];
//当前编辑的备料申请
var editReqpickm =[];


//表头宽度适应表体
function adaptTH() {
    $("table").children("thead").find("td,th").each(function () {
        var idx = $(this).index();
        var td = $(this).closest("table").children("tbody")
            .children("tr:first").children("td,th").eq(idx);
        $(this).width(td.width());
    })
};

//遮罩处理
function  mask() {
    jQuery(document).ready(function($) {
        $('.theme-login').click(function(){
            $('.theme-popover-mask').fadeIn(100);
            $('.theme-popover').slideDown(200);
        })
        $('.theme-poptit .close').click(function(){
            $('.theme-popover-mask').fadeOut(100);
            $('.theme-popover').slideUp(200);
        })
    })
}

$(function () {
	taskQuery();
    mask();
    adaptTH();

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        e.target; // 激活的标签页
        e.relatedTarget; // 前一个激活的标签页
        adaptTH();
    })

    var querytask=$("#reqmattab"),
        achievetask=$("#donetasktab"),
        reqpickm = $('#reqpickm');


    //查询生产任务
    querytask.on('click', function () {
        // alert("reqmattab");
    });

    //查询已完成生产任务
    achievetask.on('click', function () {
        // alert("achievetab");
        // adaptTH();
    });

    //保存备料申请
    reqpickm.on('click', function () {
        //如果没有备料申请处于编辑态，则不响应
        if(null == editReqpickm || editReqpickm.length==0){
            return ;
        }

        var reqBody = $("#req").find("tbody");
        var reqNums = reqBody.find("input.nnum");
        var donenum = reqBody.find("input.doneNum");
        var reqTimes = reqBody.find("input.reqtimevalue");
        
        var num;
        //校验需求重量值规范
        for(var x =0;x<reqNums.length;x++   ){
            num = reqNums[x].value - donenum[x].value;
        	if(isNaN(parseFloat(num)) || num<=0){
                alert("需求重量必须非空且大于0！")
                return;
            }
        }
        
//      //校验需求重量值规范
//        for(var x =0;x<reqNums.length;x++   ){
//            if(isNaN(parseFloat(reqNums[x].value)) || reqNums[x].value<=0){
//                alert("需求重量必须非空且大于0！")
//                return;
//            }
//        }

        //校验送达时限值规范
        for(var x =0;x<reqTimes.length;x++){
            var timeFrag = reqTimes[x].value.split(":");
            if(0>timeFrag[0] || timeFrag[0]>23 || 0>timeFrag[1] ||
                timeFrag[1]>59 || !isInteger(timeFrag[0]) || !isInteger(timeFrag[1])){
                alert("送达时限不合规范")
                return;
            }
        }

        //保存备料申请到后台
        saveReqPickm(editReqpickm);

    });



});

function sqTransbill(){
	//关闭遮罩
    $('.theme-poptit .close').click();
    selectedReqPickm.truckNum = $("#tranweightNum").val();
	saveBillRequst(selectedReqPickm);
}

function billSaved(msg){
	if (msg.error != null) {
        alert(msg.error);
        return;
    }else{
    	alert("生产转库单成功");
    }
}

//根据回传数据构造列表
function constructTask(tasks) {
	if(tasks.error){
		alert(tasks.error);
		return;
	}
    var list = tasks.datas.tasks;
    if(null == list || list.length ==0){
        return;
    }
    var tbody = $("#task").find("tbody").empty();
    var result = "";
    for (var x in list) {
        if (x % 2 == 0) {
            result += "<tr class='success'";
        } else {
            result += "<tr";
        }
        result +=" onclick='rowClick(this)'>";
        result += "<td class='task_checkbox'><input class='taskselected' type='checkbox' disabled='disabled' value=''>"
            + "<div class='billid' style='display: none'>" + list[x].billid + "</div>"
            + "<div class='matcode' style='display: none'>" + list[x].matinfo.matcode + "</div>"
            + "<div class='cpickmid' style='display: none'>" + list[x].cpickmid + "</div>"
            + "<div class='hvbillcode' style='display: none'>" + list[x].hvbillcode + "</div>"
            + "<div class='cpickm_bid' style='display: none'>" + list[x].cpickm_bid + "</div>"
            + "<div class='vrowno' style='display: none'>" + list[x].vrowno + "</div>"
            + "<div class='matpk' style='display: none'>" + list[x].matinfo.pk + "</div>"
            + "</td>"
            + "<td class='macvbillcode'>" + list[x].macvbillcode + "</td>"
            + "<td class='machine'>" + list[x].workcenter.name + "</td>"
            + "<td class='matname'>" + list[x].matinfo.matname + "</td>"
            + "<td class='matspec'>" + list[x].matinfo.matspec + "</td>"
            + "<td class='mattype'>" + list[x].matinfo.mattype + "</td>"
            + "<td class='reqnum'><div class='nnum'>" + list[x].reqNum + "</div><div class='unit'>"+ list[x].matinfo.dw+"</div></td>"
            + "<td class='reqnaccoutnum'><div class='naccoutnum'>" + list[x].naccoutnum + "</div><div class='unit'>"+ list[x].matinfo.dw+"</div></td>"
            + "<td class='starttime'>" + list[x].starttime + "</td>"
            + "<td class='ylstatus'>" + "未要料" + "</td>"
            + "<td class='status'>" + list[x].status + "</td>";
        result += "</tr>";

    }
    tbody.append(result);
    adaptTH();
}


//备料申请后台保存成功
function reqPickmSaved(msg) {
    if(msg == "error"){
        alert("后台服务出错，请稍后重试！");
        return;
    }

    //修改生成任务列表选中行状态
    var taskBody=$("#task").find("tbody");
    var trow = taskBody.find("tr");
    var taskStatus = taskBody.find("tr td.status");
    for(var x in selectedTask){
        //修改状态
        taskStatus[selectedTask[x].rowNo].innerText="要料中";
    }

    //修改备料申请状态
    var reqBody = $("#req").find("tbody");
    var checkboxes = reqBody.find(".task_checkbox");
    var reqNums = reqBody.find("input.nnum");
    var reqTimes = reqBody.find("input.reqtimevalue");
    var reqdoneNum = reqBody.find("input.doneNum");
    var listLength = checkboxes.length-reqNums.length-1;
    //由编辑态转为显示态
    for(var x in editReqpickm){
        var rowNo = editReqpickm[x].editRowNo;
        for(var i in msg){
            if(rowNo == msg[i].editRowNo){
                checkboxes[rowNo].children[1].innerText = msg[i].billid;
                checkboxes[rowNo].children[2].innerText = msg[i].rowNo;
            }
        }
        reqNums[rowNo-listLength].outerHTML ="<div class='nnum'>" + reqNums[rowNo-listLength].value+ "</div>";
        reqdoneNum[rowNo-listLength].outerHTML ="<div class='doneNum'>" + reqdoneNum[rowNo-listLength].value+ "</div>";
        reqTimes[rowNo-listLength].outerHTML = reqTimes[rowNo-listLength].value;
        changeStatus(rowNo,"要料中");
        if(rowNo%2==1){
            reqBody.find("tr")[rowNo].className = "success";
        }else{
            reqBody.find("tr")[rowNo].className = "";
        }
    }
    //清空编辑态备料申请
    editReqpickm.splice(0,editReqpickm.length);

    //清空选中任务
    selectedTask.splice(0,selectedTask.length);

    adaptTH();
}

//备料申请操作失败
function reqPickmFailed() {
    alert("无法连接到服务器，请稍后重试！");
}

//变更备料申请状态
function changeStatus(row, statusText) {
    var status =  $("#req").find("tbody").find(".status");
    status[row].innerHTML=statusText;
}


//任务列表行点击处理
function rowClick(tableRow) {
    var col =tableRow.childNodes;
    var checkbox = col[0];
    if(checkbox.children.length <=2){
        return;
    }
    
    //如果checkbox未被选中，则选中，加入到被选中任务数组
    if(!checkbox.firstChild.checked){
//    	//只支持选择一种物料需求--begin
//    	$('#task').find('.taskselected').attr('checked',false);
    	//只支持选择一种物料需求--end
        checkbox.firstChild.checked = true;
        var macvbillcode = tableRow.childNodes[1].innerText;
        var matCode = checkbox.lastChild.innerText;
        var cpickmid=checkbox.childNodes[3].innerText;
        var hvbillcode=checkbox.childNodes[4].innerText;
        var cpickm_bid=checkbox.childNodes[5].innerText;
        var vrowno=checkbox.childNodes[6].innerText;
        //var matBatch=tableRow.childNodes[6].innerText;
        var reqNum = tableRow.childNodes[6].childNodes[0].innerText;
        var naccoutnum = tableRow.childNodes[7].childNodes[0].innerText;
        var task= {
            rowNo:tableRow.rowIndex-1,
            matCode:matCode,
            reqNum:reqNum,
            naccoutnum:naccoutnum,
            cpickmid:cpickmid,
            hvbillcode:hvbillcode,
            cpickm_bid:cpickm_bid,
            vrowno:vrowno,
            macvbillcode:macvbillcode
        };
//        //只支持选择一种物料需求--begin
//        selectedTask.splice(0,selectedTask.length);
        selectedTask.push(task);
//        if(editReqpickm&&editReqpickm[0]){
//        	var index = editReqpickm[0].editRowNo;
//            deleteEditRow(index);
//            editReqpickm.splice(0,editReqpickm.length);
//        }
        var reqPickm = constructReqPickm(tableRow);
        var editRowNo = addReqPickm([reqPickm]);
        var reqEditRow = {
            editRowNo:editRowNo,
            matCode :matCode,
            reqNum:reqPickm.reqnum,
            donenum:reqPickm.donenum,
            macvbillcode:reqPickm.macvbillcode,
            reqTime:reqPickm.reqtime,
            cpickmid:reqPickm.cpickmid,
            hvbillcode:reqPickm.hvbillcode,
            cpickm_bid:reqPickm.cpickm_bid,
            vrowno:reqPickm.vrowno
        }
        editReqpickm.push(reqEditRow);
        //只支持选择一种物料需求--end
        /*目前只支持选择某一个物料需求，此部分代码在上面重写了
        selectedTask.push(task);

        var hasMat = false;
        var matRow = -1;

        //检查备料申请行，是否已有相同物料
        for(var x in editReqpickm){
            if(editReqpickm[x].matCode == matCode && editReqpickm[x].matBatch == matBatch){
                hasMat = true;
                matRow = editReqpickm[x].editRowNo;
                break;
            }
        }
        if(hasMat){
            //更新行需求重量
            updateReqNum(matRow,reqNum);
            for(var i in editReqpickm){
                if(editReqpickm[i].matCode == matCode && editReqpickm[x].matBatch == matBatch){
                    editReqpickm[i].reqNum = addReqNum(editReqpickm[i].reqNum,reqNum);
                }
            }
        }
        else {
            var reqPickm = constructReqPickm(tableRow);
            //如果没有，则添加到需求物料汇总editReqpickm
            //备料申请表汇总编辑

            var editRowNo = addReqPickm([reqPickm]);
            var reqEditRow = {
                editRowNo:editRowNo,
                matCode :matCode,
                matBatch:matBatch,
                reqNum:reqPickm.reqnum,
                reqTime:reqPickm.reqtime,
                cpickmid:reqPickm.cpickmid,
                hvbillcode:reqPickm.hvbillcode,
                cpickm_bid:reqPickm.cpickm_bid,
                vrowno:reqPickm.vrowno
            }
            editReqpickm.push(reqEditRow);
        }*/

    }
    //如果checkbox已被选中，则弃选，正在编辑的备料计划需求重量减去该行任务需求重量
    else{
        checkbox.firstChild.checked = false;
        var rowNo = tableRow.rowIndex-1;
        var operateTask=null;
        for(var i=0;i<selectedTask.length;i++){
            if(selectedTask[i].rowNo ==  rowNo){
            	operateTask =selectedTask[i];
                selectedTask.splice(i,1);
                break;
            }
        }
        for(var j=0;j<editReqpickm.length;j++){
            if(editReqpickm[j].cpickm_bid ==  operateTask.cpickm_bid){
            	editReqpickm.splice(j,1);
                break;
            }
        }
        deleteRow(operateTask);
        //目前只支持选择一种物料需求--end
        /*目前只支持选择一种物料需求，此部分代码在上面重写
        //从被选中任务数组中删除
        var rowIndex = tableRow.rowIndex-1;
        var operateTask=null;
        for(var i=0;i<selectedTask.length;i++){
            if(selectedTask[i].rowNo ==  rowIndex){
                operateTask =selectedTask[i];
                selectedTask.splice(i,1);
                break;
            }
        }

        var index = -1;
        //备料申请减去相应需求重量，若重量<=0，删除该备料申请行
        for(var i=0;i<editReqpickm.length;i++){
            if(operateTask.matCode == editReqpickm[i].matCode && operateTask.matBatch ==editReqpickm[i].matBatch){
                if(editReqpickm[i].reqNum - operateTask.reqNum<=0){
                    index = editReqpickm[i].editRowNo;
                    deleteEditRow(index);
                    editReqpickm.splice(i,1);
                }else{
                    editReqpickm[i].reqNum -= operateTask.reqNum;
                    updateReqNum(editReqpickm[i].editRowNo,0-operateTask.reqNum);
                }
                break;
            }
        }
        if(index !=-1){
            for(var x in editReqpickm){
                if(editReqpickm[x].editRowNo >index){
                    editReqpickm[x].editRowNo -=1;
                }
            }
        }*/
    }
    adaptTH();
}

//删除备料计划编辑行
function deleteEditRow(row) {
    var tBody = $("#req").find("tbody");
    tBody[0].removeChild(tBody[0].children[row]);
}

//删除备料计划行
function deleteRow(row) {
	var tBody = $("#req").find("tbody");
//	alert(row.matCode);
//	alert(row.macvbillcode);
	for(var i = 0;i<tBody[0].childElementCount-1;i++){
//		alert(tBody[0].children[i].children[0].children[4].innerText);
//		alert(tBody[0].children[i].children[1].innerText);
		if((row.macvbillcode == tBody[0].children[i].children[1].innerText)&&(row.matCode==tBody[0].children[i].children[0].children[4].innerText)){
			break;
		}
	}
    tBody[0].removeChild(tBody[0].children[i]);
}

//从备料计划选中行构造备料申请需要的数据
function constructReqPickm(tableRow) {
    var pickm = {
        billid:"",
        matcode:"",
        matname:"",
        matspec:"",
        mattype:"",
        matunit:"",
        donenum:"",
        macvbillcode:"",
        reqnum:"",
        reqtime:"",
        cpickmid:"",
        hvbillcode:"",
        cpickm_bid:"",
        vrowno:""
    };
        pickm.matcode=tableRow.childNodes[0].lastChild.innerText;
        pickm.matname=tableRow.childNodes[3].innerText;
        pickm.matspec=tableRow.childNodes[4].innerText;
        pickm.mattype=tableRow.childNodes[5].innerText;
        //pickm.matbatch=tableRow.childNodes[6].innerText;
        pickm.reqnum=tableRow.childNodes[6].childNodes[0].innerText;
        pickm.donenum=tableRow.childNodes[7].childNodes[0].innerText;
        pickm.macvbillcode=tableRow.childNodes[1].innerText;
        pickm.matunit=tableRow.childNodes[6].childNodes[1].innerText;
        var time = tableRow.childNodes[8].innerText;
        time = getReqTime(time);
        pickm.reqtime=time;
        pickm.cpickmid=tableRow.childNodes[0].childNodes[3].innerText;
        pickm.hvbillcode=tableRow.childNodes[0].childNodes[4].innerText;
        pickm.cpickm_bid=tableRow.childNodes[0].childNodes[5].innerText;
        pickm.vrowno=tableRow.childNodes[0].childNodes[6].innerText;
        return pickm;
}

//从开工时间前推半个小时得到送达时限
function  getReqTime(startTime) {
	var myDate=new Date(startTime);
	myDate.setMinutes(myDate.getMinutes()-30);
	var minutes = myDate.getMinutes();
    if(minutes<10){
        minutes = "0"+minutes;
    }
    return myDate.getHours()+":"+minutes;
	/*
    var hm = startTime.split(":");
    var myDate = new Date();
    myDate.setHours(hm[0]);
    myDate.setMinutes(hm[1]-30);
    var minutes = myDate.getMinutes();
    if(minutes<10){
        minutes = "0"+minutes;
    }
    return myDate.getHours()+":"+minutes;
    */
}

//更新备料申请行需求重量
function  updateReqNum(row,updateNum) {
    var editRow = $("#req").find("tbody").children()[row];
    var reqNumTD = editRow.children[5];
    reqNumTD.children[0].value = ""+(addReqNum((reqNumTD.children[0].value) ,updateNum));
}

//申请重量累加
function  addReqNum(req,update) {
    return parseFloat(req)+parseFloat(update);
}


//备料申请新增行,编辑态
function addReqPickm(reqpickm) {
    var tBody = $("#req").find("tbody");
    //var addRow = tBody[0].lastElementChild.outerHTML;
    //tBody.empty();
    //alert("success3");
    var result ="";
    for(var x in reqpickm){
        result += "<tr class='warning'";
        result +=" onclick='reqRowClick(this)'>";
        result +="<td class='task_checkbox'><input class='reqselected' type='checkbox' disabled='disabled' value=''>"
            +"<div class='billid' style='display: none'>" + reqpickm[x].billid + "</div>"
            +"<div class='cpickmid' style='display: none'>" + reqpickm[x].cpickmid + "</div>"
            +"<div class='reqRowNo' style='display: none'></div>"
            + "<div class='matcode' style='display: none'>" + reqpickm[x].matcode + "</div>"
            + "</td>"
            +"<td class='macvbillcode'>"+reqpickm[x].macvbillcode+"</td>"
            +"<td class='matname'>"+reqpickm[x].matname+"</td>"
            +"<td class='matspec'>"+reqpickm[x].matspec+"</td>"
            +"<td class='mattype'>"+reqpickm[x].mattype+"</td>"
            +"<td class='reqnum'><input class='nnum' type='number' value='"+reqpickm[x].reqnum
            + "'/><div class='unit'>"+reqpickm[x].matunit+"</div></td>"
            +"<td class='reqtime' ><input class='reqtimevalue' type='time' value='"+reqpickm[x].reqtime+"'/></td>"
            +"<td class='reqdoneNum'><input class='doneNum' type='number' value='"+reqpickm[x].donenum
            + "'/><div class='unit'>"+reqpickm[x].matunit+"</div></td>"
            +"<td class='status'>"+"编辑&nbsp&nbsp&nbsp&nbsp"
            +"<button class='btn btn-mini reqpickmButton' type='button' onclick='rowDeleteClick(this)'>-</button></td>"
            +"</tr>";
    }
    //result = addRow + result;
    //tBody.empty();
    tBody.append(result);
    //alert("success2");
    return tBody.childElementCount-1;
}

//判断是否是整数
function isInteger(obj) {
    return Math.floor(obj) === parseFloat(obj);
}

//备料申请删除行
function rowDeleteClick(button) {
    var rowNo=button.parentNode.parentNode.rowIndex-1;
    //删除对应的任务
    var matCode = editReqpickm[rowNo].matCode;
    var matBatch = editReqpickm[rowNo].matBatch;
    var trs = $("#task tbody tr");
    if(selectedTask.length>0){
        for(var x in selectedTask){
            if(selectedTask[x].matCode == matCode && selectedTask[x].matBatch==matBatch){
                trs[selectedTask[x].rowNo].childNodes[0].firstChild.checked = false;
                selectedTask.splice(x,1)
                x--;
            }
        }
    }
    //当前编辑备料申请表删除该行
    var index = editReqpickm[rowNo].editRowNo;
    deleteEditRow(index);
    editReqpickm.splice(index,1);
    //更新当前编辑备料申请表中其它行的editRowNo
    if(index !=-1){
        for(var x in editReqpickm){
            if(editReqpickm[x].editRowNo >index){
                editReqpickm[x].editRowNo -=1;
            }
        }
    }
    adaptTH();
}

//当前选中备料计划
var selectedReqPickm = {
	selectRows: new Array()
};

//行点击处理
function reqsqRowClick(tablerow) {
    var col = tablerow.childNodes;
    var rowIndex = tablerow.rowIndex - 1;
    var checkbox = col[0];
    
    //如果没有其它选中行,存入备料计划选中集合
    if (selectedReqPickm.selectRows.length == 0) {
    	selectedReqPickm.selectRows.push(rowIndex);
        checkbox.firstChild.checked = true;
    } else {
        if (!checkbox.firstChild.checked) {
        	checkbox.firstChild.checked = true;
        	selectedReqPickm.selectRows.push(rowIndex);
        }
        //如果点击行被选中，弃选该行
        else {
            checkbox.firstChild.checked = false;
            for (var i = 0; i < selectedReqPickm.selectRows.length; i++) {
                if (selectedReqPickm.selectRows[i] == rowIndex) {
                	selectedReqPickm.selectRows.splice(i, 1);
                    break;
                }
            }
        }
    }
}

function comfirmTrans(){
	//跳转到领料确认终端
    window.location.href = "LoadComfirmTrans";
}